package com.epoint.mobileoa.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.telephony.SmsManager;
import android.text.Html;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 通用方法
 * @author liyc
 */
public class Service {

	/**
	 * 网络信号的检测
	 * @param context
	 * @return
	 */

	public static boolean checkNet(Context context)
	{// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理） 
		try { 
			ConnectivityManager connectivity = (ConnectivityManager) context 
					.getSystemService(Context.CONNECTIVITY_SERVICE); 
			if (connectivity != null) { 
				// 获取网络连接管理的对象 
				NetworkInfo info = connectivity.getActiveNetworkInfo(); 
				if (info != null&& info.isConnected()) { 
					// 判断当前网络是否已经连接 
					if (info.getState() == NetworkInfo.State.CONNECTED) { 
						return true; 
					}       
				}       
			} 
		} catch (Exception e){
		} 
		return false; 
	}

	/**
	 * 对话框
	 * @param con
	 * @param title
	 * @param msg
	 */
	public static void Alert(Context con,String title,String msg,int icon){
		if(title==null||"".equals(title)){
			title = "提示";
		}
		AlertDialog.Builder ab = new AlertDialog.Builder(con);
		ab.setIcon(icon);
		ab.setTitle(title);
		ab.setMessage(msg);
		ab.setPositiveButton("确定", null);
		ab.create().show();
	}

	public static void AlertWithLayout(Context con,int layout,int icon){
		LayoutInflater inflater = LayoutInflater.from(con);
		View view = inflater.inflate(layout, null);
		AlertDialog ad = new AlertDialog.Builder(con)
		.setTitle("欢迎登录")
		.setView(view)
		.setPositiveButton("确定", null)
		.setNegativeButton("取消", null)
		.create();
		ad.show();
	}

	public static void AlertWithTextView(Context con,int layoutid,int tvid,String title,String msg,int icon){
		LayoutInflater inflater = LayoutInflater.from(con);
		LinearLayout ll = (LinearLayout) inflater.inflate(layoutid, null);
		TextView tv = (TextView) ll.findViewById(tvid);
		tv.setText(Html.fromHtml(msg));
		AlertDialog ad = new AlertDialog.Builder(con)
		.setIcon(icon)
		.setTitle(title)
		.setView(ll)
		.setPositiveButton("确定", null)
		.create();
		ad.show();
	}

	/**
	 * 带图标的对话框
	 * 上下文Activity，布局文件，内容id，图片id，内容，图片资源
	 */
	public void showCustomDialog(Activity con,int reslayout,int tv,int img,String msg,int imgsrc)  
	{ 
		AlertDialog.Builder builder = new AlertDialog.Builder(con);  
		LayoutInflater inflater = con.getLayoutInflater();
		View layout = inflater.inflate(reslayout,null);//LayoutInflater inflater = (LayoutInflater)con.getSystemService(LAYOUT_INFLATER_SERVICE);
		TextView text = (TextView) layout.findViewById(tv);  
		text.setText(msg);
		ImageView image = (ImageView) layout.findViewById(img);  
		image.setImageResource(imgsrc); 
		builder.setView(layout);
		builder.setPositiveButton("确定", null);
		builder.create().show();
	}

	/**
	 * 电话拨打
	 * @param con
	 * @param phonenum
	 */
	public static void Call(Context con,String phonenum){
		Intent intent = new Intent();
		intent.setAction("android.intent.action.CALL");
		intent.setData(Uri.parse("tel:"+ phonenum));
		con.startActivity(intent);
	}

	/**
	 * 发送短信
	 * @param con
	 * @param phonenum
	 * @param shortmsg
	 */
	public static void SendMsg(Context con,String phonenum,
			String shortmsg) {
		SmsManager smsMag = SmsManager.getDefault();
		List<String> texts = smsMag.divideMessage(shortmsg);
		for(String text:texts){
			smsMag.sendTextMessage(phonenum, null, text, null, null);
		}
	}



	/**
	 * 在线程里边创建Toast组件时，调用方法！
	 * @param con
	 * @param message
	 */
	public static void showThreadToast(final Context con,final String message,int time) {
		Handler handler = new Handler();
		handler.post(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(con.getApplicationContext(), message,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 在线程里边创建Dialog组件时，调用方法！
	 * @param con
	 * @param message
	 */
	public static void showThreadDialog(final Context con,final String message,final int icon){
		Handler handler = new Handler();
		handler.post(new Runnable() {
			@Override
			public void run() {
				Alert(con.getApplicationContext(), null, message,icon);
			}
		});
	}

	public static void showTextAlert(Context con,String title,String text,int icon){
		TextView tv = new TextView(con);
		tv.setTextColor(Color.YELLOW);
		tv.setTextSize(18);
		tv.setText(text);
		tv.setScroller(new Scroller(con));
		ScrollView sv = new ScrollView(con);
		sv.addView(tv);
		AlertDialog ad = new AlertDialog.Builder(con)
		.setIcon(icon)
		.setTitle(title)
		.setView(sv)
		.setPositiveButton("确定", null)
		// .setNegativeButton("取消", null)
		.create();
		ad.show();
	}
	public static String getTimeFromDate(Date date,int type){
		String year = formatTimeStr(String.valueOf(date.getYear()));
		String month = formatTimeStr(String.valueOf(date.getMonth()));
		String day = formatTimeStr(String.valueOf(date.getDate()));
		String hours = formatTimeStr(String.valueOf(date.getHours()));
		String minutes = formatTimeStr(String.valueOf(date.getMinutes()));
		String seconds = formatTimeStr(String.valueOf(date.getSeconds()));
		if(type==1){
			return year+"."+month+"."+day+" "+hours+":"+minutes+":"+seconds;
		}
		else if(type==2){
			return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds+":";
		}
		else{
			return year+"年"+month+"月"+day+"日"+hours+"时"+minutes+"分"+seconds+"秒";
		}
	}

	public static String TimeFormat(long dateTaken) {
		return DateFormat.format("yyyy.MM.dd kk:mm:ss", dateTaken).toString();
	} 

	public static String TimeFormat2(long dateTaken) {
		return DateFormat.format("yyyyMMddkkmmss", dateTaken).toString();
	} 

	public static String TimeFormatForDate(Date date,String format){
		return DateFormat.format(format, date).toString();
	}



	/**
	 * 获取时间字符串
	 * @return
	 */
	public static String getTimeStr(int type){
		Time t = new Time();
		t.setToNow();
		String yearStr = formatTimeStr(String.valueOf(t.year));
		String monthStr = formatTimeStr(String.valueOf(t.month+1));
		String dayStr = formatTimeStr(String.valueOf(t.monthDay));
		String hourStr = formatTimeStr(String.valueOf(t.hour));
		String minuteStr = formatTimeStr(String.valueOf(t.minute));
		String secondStr = formatTimeStr(String.valueOf(t.second));
		if(type==1){
			return yearStr+"年"+monthStr+"月"+dayStr+"日"+hourStr+"时"+minuteStr+"分"+secondStr+"秒";
		}
		else{
			return yearStr+monthStr+dayStr+hourStr+minuteStr+secondStr;
		}
	}

	/**
	 * 格式化时间字符串
	 * @param timeStr
	 * @return
	 */
	public static String formatTimeStr(String timeStr){
		if(timeStr.length()==1){
			return "0"+timeStr;
		}
		else{
			return timeStr;
		}
	}

	/**
	 * android获取一个用于打开HTML文件的intent
	 * @param param
	 * @return
	 */
	public static Intent getHtmlFileIntent(String param)
	{
		Uri uri = Uri.parse(param ).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param ).build();
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.setDataAndType(uri, "text/html");
		return intent;
	}

	/**
	 * android获取一个用于打开图片文件的intent
	 * @param param
	 * @return
	 */
	public static Intent getImageFileIntent(String param)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "image/*");
		return intent;
	}

	/**
	 * android获取一个用于打开PDF文件的intent
	 * @param param
	 * @return
	 */
	public static Intent getPdfFileIntent(String param)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "application/pdf");
		return intent;
	}

	/**
	 * android获取一个用于打开文本文件的intent
	 * @param param
	 * @param paramBoolean
	 * @return
	 */
	public static Intent getTextFileIntent(String param, boolean paramBoolean)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (paramBoolean)
		{
			Uri uri1 = Uri.parse(param );
			intent.setDataAndType(uri1, "text/plain");
		}
		else
		{
			Uri uri2 = Uri.fromFile(new File(param ));
			intent.setDataAndType(uri2, "text/plain");
		}

		return intent;
	}

	/**
	 * android获取一个用于打开音频文件的intent
	 * @param param
	 * @return
	 */
	public static Intent getAudioFileIntent(String param)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "audio/*");
		return intent;
	}

	/**
	 * android获取一个用于打开视频文件的intent
	 * @param param
	 * @return
	 */
	public static Intent getVideoFileIntent(String param)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "video/*");
		return intent;
	}

	//android获取一个用于打开CHM文件的intent
	public static Intent getChmFileIntent(String param)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "application/x-chm");
		return intent;
	}

	/**
	 * android获取一个用于打开Word文件的intent
	 * @param param
	 * @return
	 */
	public static Intent getWordFileIntent(String param)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/msword");
		return intent;
	}

	/**
	 * android获取一个用于打开Excel文件的intent
	 * @param param
	 * @return
	 */
	public static Intent getExcelFileIntent(String param,Context con)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "application/vnd.ms-excel");
		return intent;
	}

	/**
	 * android获取一个用于打开PPT文件的intent
	 * @param param
	 * @return
	 */
	public static Intent getPptFileIntent(String param)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
		return intent;
	}
	
	public static Intent getRARFileIntent(String param){
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param ));
		intent.setDataAndType(uri, "application/x-rar-compressed");
//		intent.setAction("com.asrazpaid");
		System.out.println("uncompass RAR");
		return intent;
	}

	/**寻找适合的程序打开文件*/
	@SuppressWarnings("unused")
	private String tag = "FileDialog";
	public final static boolean D = false;
	public static void doOpenFile2(Context con,String attachfilepath){
		String suffix = attachfilepath.substring(attachfilepath.lastIndexOf("."),attachfilepath.length()).toLowerCase();
		Intent intent = new Intent(Intent.ACTION_VIEW);
		String param = "file://" + attachfilepath;
		Uri uri = Uri.parse(param);
		String type = null;
		type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
				MimeTypeMap.getFileExtensionFromUrl(attachfilepath));
		System.out.println("filetype:"+type);
		if (type == null) {
			String tmp = attachfilepath.toLowerCase();
			if (tmp.endsWith("mp3") || tmp.endsWith("wav") || tmp.endsWith("wma")) {
				type = "audio/*";
			} else if (tmp.endsWith("apk")) {
				type = "application/vnd.android.package-archive";
			}
		}
		if(type != null&&!suffix.equals(".rar")){
			intent.setDataAndType(uri, type);
			
			try {
				((Activity) con).startActivityForResult(intent, 1);
			} catch (ActivityNotFoundException e){
				Toast.makeText(con, 
						"文件不能打开",
						Toast.LENGTH_SHORT).show();
			}
		} 
		/*else if(suffix.equals(".rar")){
			intent.setDataAndType(uri, type);
			intent.setAction("com.asrazpaid");
			try {
				((Activity) con).startActivityForResult(intent, 1);
			} catch (ActivityNotFoundException e){
				Toast.makeText(con, 
						"RAR不能打开",
						Toast.LENGTH_SHORT).show();
			}
		}*/
		else {
			try{
				Intent intent1 = null;

				if(suffix.equals(".jpg")||suffix.equals(".png")||suffix.equals(".gif")||suffix.equals(".bmp")){
					intent1 = Service.getImageFileIntent(attachfilepath);
				}
				else if(suffix.equals(".pdf")){
					intent1  = Service.getPdfFileIntent(attachfilepath);
				}
				else if(suffix.equals(".doc")||suffix.equals(".docx")){
					intent1  = Service.getWordFileIntent(attachfilepath);
				}
				else if(suffix.equals(".xls")||suffix.equals(".xlsx")){
					intent1  = Service.getExcelFileIntent(attachfilepath,con);
				}
				else if(suffix.equals(".mp3")||suffix.equals(".wma")||suffix.equals(".mp4")||suffix.equals(".wav")){
					intent1  = Service.getAudioFileIntent(attachfilepath);
				}
				else if(suffix.equals(".txt")){
					intent1  = Service.getTextFileIntent(attachfilepath, false);
				}
				else if(suffix.equals(".html")){
					intent1  = Service.getHtmlFileIntent(attachfilepath);
				}
				else if(suffix.equals(".ppt")||suffix.equals(".pptx")){
					intent1  = Service.getPptFileIntent(attachfilepath);
				}
				else if(suffix.equals(".rar")||suffix.equals(".zip")){
					intent1  = Service.getRARFileIntent(attachfilepath);
				}
				con.startActivity(intent1);
			}catch(Exception e){
				Toast.makeText(con, "没有适合的程序打开此文件", 1000).show();
				System.out.println((e.getMessage()==null?"":"\n"+e.getMessage()));
			}
		}
	}

	/**
	 * 完成退出应用程序
	 */
	public static void quitApp(Context con){
		ActivityManager activityMgr= (ActivityManager) con.getSystemService(Context.ACTIVITY_SERVICE); 
		activityMgr.restartPackage(con.getPackageName()); 
	}

	//读取文件中字符串
	public static String readtxt(String path){
		try {
			BufferedReader br= new BufferedReader(new FileReader(path));
			String str="";
			String r=br.readLine();
			while(r!=null){
				str+=r;
				r=br.readLine();
			}
			return str;
		} catch (Exception e) {
			return "";
		}
	}

	//拷贝文件
	public static void copyFileTemp(String src, String dest) { 
		InputStream is = null;   
		OutputStream os = null;   
		char ch[] = src.toCharArray();   

		// ************新添加的代码,获取文件名**********   
		int pos = 0;   
		for (int i = ch.length - 1; i >= 0; i--) {   
			if (ch[i] == '\\') {   
				if (i > pos)   
					pos = i;   
			}   
		}   
		String temp = src.substring(pos);   
		dest = dest + temp;   
		System.out.println("dest=" + dest);   

		try {   
			is = new BufferedInputStream(new FileInputStream(src));   
			os = new BufferedOutputStream(new FileOutputStream(dest));   

			byte[] b = new byte[1024];   
			int len = 0;   

			try {   
				while ((len = is.read(b)) != -1) {   
					os.write(b, 0, len);   
				}   
				os.flush();   
			} catch (IOException e) {   
				e.printStackTrace();   
			} finally {   
				if (is != null) {   
					try {   
						is.close();   
					} catch (IOException e) {   
						e.printStackTrace();   
					}   
				}   
			}   
		} catch (FileNotFoundException e) {   
			e.printStackTrace();   
		} finally {   
			if (os != null) {   
				try {   
					os.close();   
				} catch (IOException e) {   
					e.printStackTrace();   
				}   
			}   
		}   
	}

	/**
	 * 从assets拷贝文件到文件夹
	 * @param con
	 * @param assfilename
	 * @param destpathname
	 * @throws IOException 
	 */
	public static void copyFileFromAss2Dir(Context con,String assfilename,String destpathname) throws IOException{
			InputStream fis = con.getResources().getAssets().open(assfilename);
			FileOutputStream fos = new FileOutputStream(destpathname);
			byte data[] = new byte[1024];
			int count;
			while ((count = fis.read(data)) != -1) {
				fos.write(data, 0, count);
			}
			fos.flush();
			fos.close();
			fis.close();
	}

	/**
	 * 拷贝文件
	 * @param con
	 * @param assfilename
	 * @param destpathname
	 * @throws IOException 
	 */
	public static void copyFile(String assfilename,String destpathname) throws IOException{
		FileInputStream fis = new FileInputStream(assfilename);
		FileOutputStream fos = new FileOutputStream(destpathname);
		byte data[] = new byte[1024];
		int count;
		while ((count = fis.read(data)) != -1) {
			fos.write(data, 0, count);
		}
		fos.flush();
		fos.close();
		fis.close();
	}

	public static String getIp(String seamurl){
		return seamurl.substring(0,seamurl.indexOf("MobileOA"));
	}

	public static String getTagElementString(String tag,String head,String tail){
		return tag.substring(tag.indexOf(head)+head.length(),tag.indexOf(tail));
	}

	/**
	 * 判断跳转到哪个视图
	 */
//	public static void TurnMainView(Activity nowview,Class<?> view1,Class<?> view2,String dbname){
//		String viewtype = DbUtil.getViewType(nowview, dbname);
//		System.out.println("---viewtype---"+viewtype);
//		System.out.println(nowview.getClass().getName());
//		if(viewtype.equals("1")){
//			Intent it = new Intent(nowview, view1);
//			if(nowview.getClass().getName().equals("com.epoint.mobileoa.view.login.LoginView")){
//				nowview.startActivity(it);
//			}
//			else{
//				nowview.startActivityForResult(it, 0);
//			}
//		}
//		else{
//			Intent it = new Intent(nowview, view2);
//			if(nowview.getClass().getName().equals("com.epoint.mobileoa.view.login.LoginView")){
//				nowview.startActivity(it);
//			}
//			else{
//				nowview.startActivityForResult(it, 0);
//			}
//		}
//
//	}

	public static void playMusic(Context con,String filename) throws IOException{
		MediaPlayer m = new MediaPlayer();
		AssetFileDescriptor descriptor = con.getAssets().openFd(
				filename);
		m.setDataSource(descriptor.getFileDescriptor(),
				descriptor.getStartOffset(), descriptor.getLength());
		descriptor.close();
		m.prepare();
		m.start();
	}

//	public static void changeLoginStatus(String seamurl,String username,String status){
//		seamurl += "?requestType=UpdateLoginStatus&username="+username+
//				"&islogin="+status;
//		HttpTask ht = new HttpTask();
//		ht.getSeamBackStr(seamurl);
//	}

	public static void deleteFile(File file){ 
		if(file.exists()){                    //判断文件是否存在
			if(file.isFile()){                    //判断是否是文件
				file.delete();                       //delete()方法 你应该知道 是删除的意思;
			}else if(file.isDirectory()){              //否则如果它是一个目录
				File files[] = file.listFiles();               //声明目录下所有的文件 files[];
				for(int i=0;i<files.length;i++){            //遍历目录下所有的文件
					deleteFile(files[i]);             //把每个文件 用这个方法进行迭代
				} 
			} 
			file.delete(); 
		}else{ 
			System.out.println("所删除的文件不存在！"+'\n'); 
		} 
	}

	//人员选择后List转字符串
	public static String[] dealChooseListToString(List<Map<String,String>> clst){
		String snname = "";
		String sguid = "";
		int size = clst.size();
		if(size>0){
			for(int i=0;i<size;i++){
				if(i<size-1){
					snname += clst.get(i).get("name")+";";
					sguid += clst.get(i).get("guid")+";";
				}
				else if(i==size-1){
					snname += clst.get(i).get("name");
					sguid += clst.get(i).get("guid");
				}
			}
		}
		String[] info = new String[2];
		info[0] = snname;
		info[1] = sguid;
		return info;
	}
	
	public static String getXMLAtt(String tag,String att){
		String  head = "<"+att+">";
		String tail = "</"+att+">";
		return tag.substring(tag.indexOf(head)+head.length(),tag.indexOf(tail));
	}
}
